package com.baizhi.service;

import com.baizhi.dao.CategoryDao;
import com.baizhi.entity.Category;
import com.baizhi.entity.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> queryByLevels(int levels) {
        return categoryDao.queryLevels(levels);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> queryByParendId(String id) {
        return categoryDao.queryByParendId(id);
    }

    @Override
    public Map<String, Object> delete(String id) {
        /*
        * 1.先根据id查询当前类别信息
        * 2.如果是二级类别  直接删
        * 3.如果是1级类别 判断1级类别下有没有二级类别
        *               有  不能删
        *               没有  可以删
        * */

        Map<String,Object> map = new HashMap<>();
        Category category = categoryDao.queryById(id);
        Integer levels = category.getLevels();
        if(levels == 1){
            //一级类别
            List<Category> categories = categoryDao.queryByParendId(id);
            if(categories.size() == 0){
                categoryDao.delete(id);
                map.put("flag",true);
            }else{
                map.put("flag","false");
                map.put("msg","无法删除因为内部存在二级类别");
            }
        }else{
            List<Video> videos = categoryDao.queryCategoryVideo(category.getId());
            if(videos.size() == 0){
                categoryDao.delete(id);
            }else{
                map.put("flag","false1");
                map.put("msg","无法删除因为有视频已使用此二级类别");
            }
        }
        return map;
    }

    @Override
    public void save(Category category) {
        category.setId(UUID.randomUUID().toString());
        System.out.println(category);
        categoryDao.save(category);
    }

    @Override
    public void updateCategory(Category category) {
        categoryDao.updateCategory(category);
    }
}
